//$(function () { plusReady(); })
function plusReady() {
    _storeid = getUrlParam("storeid");
    loadGroupByGoods();
}

var _storeid = 0, _currentcityid;

if (window.plus) {
    plusReady();
} else {
    document.addEventListener('plusready', plusReady, false);
}

// 画优惠商品列表
function loadGroupByGoods(paintstyle) {
    var pagenum = 15;
    var pagecount = generatedCount;
    if ("refresh" == paintstyle) {
        pagenum = 20;
        pagecount = 1;
    }

    $.ajax({
        type: 'Get',
        url: configManager.RequstUrl + "api/goods/list?hasstore=1&type=discount&onlysell=1&by=selled&order=desc&limit=" + pagenum + "&page=" + pagecount + "&store=" + _storeid
    }).done(function (data) {
        if (data.state != "success") { console.log(data.message); return; }
        var goodslist = data.data;
        var html = [];
        for (var i = 0; i < goodslist.length; i++) {
            var goods = goodslist[i];

            html.push("<div name='goodsItem' class='item-01-wrap' tip='" + goods.id + "'><ul class='item-01-block'>");
            html.push("<li class='img-part'> <img src='" + configManager.goodsImgurl.format(goods.pic, "184-220") + "'><b></b></li>");
            html.push("<li class='tips-part'><p><i class=\"dollar icon\"></i>消费" + goods.store.offline_pay_fee + "%</p><p><i class=\"bitcoin icon\"></i>金币" + goods.store.coin_pay_fee + "%</p></li>");

            var address = goods.store.store_address;
            if (goods.store.store_address.length > 18)
            { address = address.substr(0, 18) + '...'; }

            html.push("<li class='text-part'><h2>" + goods.title + "</h2><p>" + address + "</p><p><span style='color:#f30; font-size:1.4em;'>￥" + goods.price + "</span>&nbsp;&nbsp;<span style='color:#999;text-decoration:line-through;'>" + goods.market_price + "</span></p></li>");
            html.push("</ul></div>");
        }

        if ("append" == paintstyle) {
            // 无效加载
            if (html.length == 0) { generatedCount = generatedCount - 1; }
            $("#discountgoodlist").append($(html.join("")));
        } else {
            if (html.length == 0) { html.push("<div style='vertical-align: middle;text-align: center;padding-top: 30%;'>没有团购商品，请看看别的吧</div>"); }
            $("#discountgoodlist").html(html.join(""));
        }


        try { myScroll.refresh(); } catch (err) { }

        // 绑定跳转订单详情
        $("div[name=goodsItem]").on("click", function () {
            clicked('../mine/goods/detail.html?goodsid=' + $(this).attr("tip"), false, false, "pop-in");
        });

    });


}

var myScroll, pullDownEl, pullDownOffset, pullUpEl, pullUpOffset, generatedCount = 1;
function loaded() {

    pullDownEl = document.getElementById('pullDown');
    pullDownOffset = pullDownEl.offsetHeight;
    pullUpEl = document.getElementById('pullUp');
    pullUpOffset = pullUpEl.offsetHeight;

    myScroll = new iScroll('wrapper', {
        useTransition: false,
        topOffset: pullDownOffset,
        onRefresh: function () {
            if (pullDownEl.className.match('loading')) {
                pullDownEl.className = '';
                pullDownEl.querySelector('.pullDownLabel').innerHTML = '下拉即可刷新';
            } else if (pullUpEl.className.match('loading')) {
                pullUpEl.className = '';
                pullUpEl.querySelector('.pullUpLabel').innerHTML = '';
            }
        },
        onScrollMove: function () {
            if (this.y > 5 && !pullDownEl.className.match('flip')) {
                pullDownEl.className = 'flip';
                pullDownEl.querySelector('.pullDownLabel').innerHTML = '松开刷新...';
                this.minScrollY = 0;
            } else if (this.y < 5 && pullDownEl.className.match('flip')) {
                pullDownEl.className = '';
                pullDownEl.querySelector('.pullDownLabel').innerHTML = '下拉即可刷新...';
                this.minScrollY = -pullDownOffset;
            } else if (this.y < (this.maxScrollY - 5) && !pullUpEl.className.match('flip')) {
                pullUpEl.className = 'flip';
                if (isDisplayPullUp()) {
                    pullUpEl.querySelector('.pullUpLabel').innerHTML = '上拉加载更多';
                }
                this.maxScrollY = this.maxScrollY;
            } else if (this.y > (this.maxScrollY + 5) && pullUpEl.className.match('flip')) {
                pullUpEl.className = '';
                if (isDisplayPullUp()) {
                    pullUpEl.querySelector('.pullUpLabel').innerHTML = '加载中...';
                }
                this.maxScrollY = pullUpOffset;
            }
        },
        onScrollEnd: function () {
            if (pullDownEl.className.match('flip')) {
                pullDownEl.className = 'loading';
                pullDownEl.querySelector('.pullDownLabel').innerHTML = '加载中...';
                pullDownAction();
            } else if (pullUpEl.className.match('flip')) {
                pullUpEl.className = 'loading';
                if (isDisplayPullUp()) {
                    pullUpEl.querySelector('.pullUpLabel').innerHTML = '加载中...';
                }
                pullUpAction();
            }
        }
    });

    setTimeout(function () { document.getElementById('wrapper').style.left = '0'; }, 800);
}

function isDisplayPullUp() {
    // 屏幕高度 - 滚动Div面高度 - 上拉Div在滚动Div位置
    return ($(window).height() - $("#wrapper").offset().top - $("#pullUp").position().top) < 0;
}

document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);

document.addEventListener('DOMContentLoaded', function () { setTimeout(loaded, 200); }, false);
// 下拉刷新
function pullDownAction() {
    setTimeout(function () {
        // 检查网络状况
        if (!checkNetworkHeath()) { myScroll.refresh(); return; }
        generatedCount = 1;
        loadGroupByGoods("refresh");

    }, 1000);
}
// 上滑加载
function pullUpAction() {
    setTimeout(function () {
        generatedCount = generatedCount + 1;
        loadGroupByGoods("append");
    }, 1000);
}

function checkNetworkHeath() {
    // 判断当前网络状况
    var currentNetworkType = plus.networkinfo.getCurrentType();
    console.log("当前网络" + currentNetworkType);
    if (currentNetworkType && (plus.networkinfo.CONNECTION_UNKNOW == currentNetworkType || plus.networkinfo.CONNECTION_NONE == currentNetworkType)) {
        plus.nativeUI.alert("无网络连接！")
        return false;
    }

    return true;
}